const Excel = require('exceljs');
const JWT = require('jsonwebtoken');

module.exports = {
  // 导出excel
  async excelNew(url, req, headers, name, func) {
    console.log(111, this, 222, this.ctx)
    let columns = [];//exceljs要求的columns
    let hjRow = {};//合计行
    let titleRows = headers.length;//标题栏行数

    //处理表头
    for (let i = 0; i < titleRows; i++) {
      let row = headers[i];
      for (let j = 0, rlen = row.length; j < rlen; j++) {
        let col = row[j];
        let { f, t, w = 15 } = col;
        if (!f) continue;//不存在f则跳过

        if (col.totalRow) hjRow[f] = true;
        if (col.totalRowText) hjRow[f] = col.totalRowText;

        col.style = { alignment: { vertical: 'middle', horizontal: 'center' } };
        col.header = t;
        col.key = f;
        col.width = w;
        columns.push(col);
      }
    }

    let data = {
      data: []
    };
    if (url) {
      const result = await this.post(url, req);//请求数据
      data = result.data;
    }
    if (func) data = func(data);


    //处理合计行
    if (JSON.stringify(hjRow) != "{}") {
      let tr = {};
      for (let i = 0, len = data.data.length; i < len; i++) {
        let item = data.data[i];
        for (let key in item) {
          if (hjRow[key] === true) {
            tr[key] = (tr[key] || 0) + item[key];
            continue;
          }
          tr[key] = hjRow[key] || '';
        }
      }
      data.data.push(tr);
    }

    let workbook = new Excel.Workbook();
    let sheet = workbook.addWorksheet('My Sheet', { views: [{ xSplit: 1, ySplit: 1 }] });
    sheet.columns = columns;
    sheet.addRows(data.data);

    //处理复杂表头
    if (titleRows > 1) {
      for (let i = 1; i < titleRows; i++)  sheet.spliceRows(1, 0, []);//头部插入空行

      for (let i = 0; i < titleRows; i++) {
        let row = headers[i];
        for (let j = 0, rlen = row.length; j < rlen; j++) {
          let col = row[j];
          if (!col.m1) continue;

          sheet.getCell(col.m1).value = col.t;
          sheet.mergeCells(col.m1 + ":" + col.m2);
        }
      }
    }

    //处理样式、日期、字典项
    let that = this;
    sheet.eachRow(function (row, rowNumber) {
      //设置行高
      row.height = 25;

      row.eachCell({ includeEmpty: true }, function (cell, colNumber) {
        //设置边框 黑色 细实线
        let top = left = bottom = right = { style: 'thin', color: { argb: '000000' } };
        cell.border = { top, left, bottom, right };

        //设置标题部分为粗体
        if (rowNumber <= titleRows) { cell.font = { bold: true }; return; }

        //处理数据项里面的日期和字典
        let { type, dict } = columns[colNumber - 1];
        if (type && (cell.value || cell.value == 0)) return;//非日期、字典或值为空的直接返回
        switch (type) {
          case 'date': cell.value = that.parseDate(cell.value); break;
          case 'dict': cell.value = that.parseDict(cell.value.toString(), dict); break;
        }

      });
    });

    this.ctx.set('Content-Type', 'application/vnd.openxmlformats');
    this.ctx.set('Content-Disposition', "attachment;filename*=UTF-8' '" + encodeURIComponent(name) + '.xlsx');
    this.ctx.body = await workbook.xlsx.writeBuffer();
  },

  // 数字补0  3 ===> 03
  numberAddZero(num, digit = 2) {
    let newNum = String(num);
    let gap = digit - newNum.length;
    if (gap > 0) {
      newNum = this.range(gap).map(v => 0).join('') + newNum;
    }
    return newNum;
  },

  range(start, end) {
    if (!end) {
      end = start;
      start = 0;
    }
    return [...Array(end - start).keys()].map(v => v + start);
  },

  checkLogin(app) {
    let obj = {
      result: false,
      body: {}
    };
    // 拿到传会数据的header 中的token值
    const token = app.ctx.request.header.authorization;
    if (!token) { // 不存在token
      obj = {
        result: false,
        body: {
          status: 401,
          message: '未登录， 请先登录',
          result: null
        }
      }
    } else { // 存在token
      let decode;
      try {
        // 验证当前token
        decode = JWT.verify(token, app.config.jwt.secret);
        app.ctx.user = decode;
        obj = {
          result: true,
          body: {
            result: decode
          }
        }
      } catch (e) {
        obj = {
          result: false,
          body: {
            status: 401,
            message: '登录信息已过期，请重新登录',
            result: null
          }
        }
      }
    }
    return obj;
  },
  filterObj(obj = {}) {
    let result = {};
    for(let key in obj) {
      if (obj[key] && obj[key] !== 0 && obj[key] !== false) {
        result[key] = JSON.parse(JSON.stringify(obj[key]));
      }
    }
    return result;
  }
}
